package mvp.cklm.testtask.service;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import mvp.cklm.testtask.dao.AddressDao;
import mvp.cklm.testtask.dao.IAddressDao;
import mvp.cklm.testtask.model.AddressModel;
import mvp.cklm.testtask.model.enums.AddressRequest;
import mvp.cklm.testtask.util.IdGenerator;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: valera
 * Date: 25.02.14
 * Time: 7:30
 */
public class AddressService implements IAddressService {
    private IAddressDao addressDao;
    private IdGenerator idGenerator;

    public AddressService(MongoClient mongoClient, String dbName) {
        this.addressDao = new AddressDao(mongoClient, dbName);
        Integer maxId = addressDao.getMaxId();
        maxId = maxId == null ? 0 : maxId;
        this.idGenerator = new IdGenerator(maxId);
    }

    @Override
    public int getNextAddressId() {
        return idGenerator.getNewId();
    }

    @Override
    public long getAddressCount() {
        return addressDao.getObjectCount();
    }

    @Override
    public boolean saveAddress(AddressModel model) {
        return addressDao.saveObject(model);
    }

    @Override
    public AddressModel getAddressById(Integer key) {
        return addressDao.getObjectById(key);
    }

    @Override
    public List<AddressModel> getAddressPage(int page, int pageSize) {
        return addressDao.getPage(page, pageSize);
    }

    @Override
    public List<AddressModel> getAddressesByRequest(Map<AddressRequest, Object> req) {
        DBObject reqObj = new BasicDBObject();
        Iterator<Map.Entry<AddressRequest, Object>> iter = req.entrySet().iterator();
        Map.Entry<AddressRequest, Object> tmp;
        while (iter.hasNext()) {
            tmp = iter.next();
            reqObj.put(tmp.getKey().getFieldName(), tmp.getValue());
        }
        return addressDao.findByQuery(reqObj);
    }

    @Override
    public void cleanAddresses() {
        addressDao.dropCollection();
        idGenerator = new IdGenerator(0);
    }
}
